<template>
  <div class="developer-auth">
    <!-- 开发者密码验证对话框 -->
    <el-dialog
      v-model="showPasswordDialog"
      title="开发者工具访问验证"
      width="400px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <div class="auth-content">
        <div class="auth-icon">
          <el-icon size="48" color="#e6a23c">
            <Lock />
          </el-icon>
        </div>
        
        <div class="auth-message">
          <h3>开发者工具访问</h3>
          <p>此功能仅供开发和测试使用，需要输入开发者密码才能继续。</p>
        </div>

        <el-form @submit.prevent="handleSubmit">
          <el-form-item>
            <el-input
              v-model="password"
              type="password"
              placeholder="请输入开发者密码"
              show-password
              size="large"
              :disabled="verifying"
              @keyup.enter="handleSubmit"
            >
              <template #prefix>
                <el-icon><Key /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          
          <div class="auth-actions">
            <el-button @click="handleCancel" :disabled="verifying">
              取消
            </el-button>
            <el-button 
              type="primary" 
              :loading="verifying"
              @click="handleSubmit"
            >
              验证
            </el-button>
          </div>
        </el-form>
      </div>
    </el-dialog>

    <!-- 会话状态指示器 -->
    <div v-if="isAuthenticated" class="session-indicator">
      <el-tag type="success" size="small">
        <el-icon><CircleCheck /></el-icon>
        开发者模式
      </el-tag>
      <el-button 
        type="danger" 
        size="small" 
        text
        @click="logout"
      >
        退出
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Lock, Key, CircleCheck } from '@element-plus/icons-vue'
import { request } from '@/utils/request'

// Props
interface Props {
  modelValue: boolean
  onSuccess?: () => void
  onCancel?: () => void
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false
})

// Emits
const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'success': [sessionToken: string]
  'cancel': []
}>()

// 响应式数据
const showPasswordDialog = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const password = ref('')
const verifying = ref(false)
const sessionToken = ref<string | null>(null)
const sessionCheckTimer = ref<NodeJS.Timeout | null>(null)

// 计算属性
const isAuthenticated = computed(() => !!sessionToken.value)

// 方法
const handleSubmit = async () => {
  if (!password.value.trim()) {
    ElMessage.warning('请输入开发者密码')
    return
  }

  verifying.value = true

  try {
    const response = await request.post('/developer/auth/verify', {
      password: password.value
    })

    if (response.success) {
      sessionToken.value = response.sessionToken
      
      // 保存到localStorage
      localStorage.setItem('developer_session_token', response.sessionToken)
      
      ElMessage.success('开发者认证成功')
      
      // 关闭对话框
      showPasswordDialog.value = false
      password.value = ''
      
      // 启动会话检查
      startSessionCheck()
      
      // 触发成功回调
      emit('success', response.sessionToken)
      props.onSuccess?.()
      
    } else {
      ElMessage.error(response.message || '密码验证失败')
    }

  } catch (error) {
    console.error('开发者认证失败:', error)
    ElMessage.error('认证失败，请稍后重试')
  } finally {
    verifying.value = false
  }
}

const handleCancel = () => {
  showPasswordDialog.value = false
  password.value = ''
  emit('cancel')
  props.onCancel?.()
}

const logout = async () => {
  try {
    if (sessionToken.value) {
      await request.post('/developer/auth/logout', {
        sessionToken: sessionToken.value
      })
    }
  } catch (error) {
    console.error('退出开发者模式失败:', error)
  } finally {
    // 清理本地状态
    sessionToken.value = null
    localStorage.removeItem('developer_session_token')
    stopSessionCheck()
    
    ElMessage.info('已退出开发者模式')
  }
}

const validateSession = async (token: string): Promise<boolean> => {
  try {
    const response = await request.post('/developer/auth/validate', {
      sessionToken: token
    })
    
    return response.valid === true
  } catch (error) {
    console.error('会话验证失败:', error)
    return false
  }
}

const startSessionCheck = () => {
  // 每5分钟检查一次会话有效性
  sessionCheckTimer.value = setInterval(async () => {
    if (sessionToken.value) {
      const isValid = await validateSession(sessionToken.value)
      if (!isValid) {
        ElMessage.warning('开发者会话已过期，请重新认证')
        logout()
      }
    }
  }, 5 * 60 * 1000) // 5分钟
}

const stopSessionCheck = () => {
  if (sessionCheckTimer.value) {
    clearInterval(sessionCheckTimer.value)
    sessionCheckTimer.value = null
  }
}

// 获取当前会话令牌
const getCurrentSessionToken = (): string | null => {
  return sessionToken.value
}

// 检查是否已认证
const checkAuthenticated = (): boolean => {
  return isAuthenticated.value
}

// 生命周期
onMounted(() => {
  // 尝试从localStorage恢复会话
  const savedToken = localStorage.getItem('developer_session_token')
  if (savedToken) {
    validateSession(savedToken).then(isValid => {
      if (isValid) {
        sessionToken.value = savedToken
        startSessionCheck()
      } else {
        localStorage.removeItem('developer_session_token')
      }
    })
  }
})

onUnmounted(() => {
  stopSessionCheck()
})

// 暴露方法给父组件
defineExpose({
  getCurrentSessionToken,
  checkAuthenticated,
  logout
})
</script>

<style scoped lang="scss">
.developer-auth {
  .auth-content {
    text-align: center;
    padding: 20px 0;
    
    .auth-icon {
      margin-bottom: 20px;
    }
    
    .auth-message {
      margin-bottom: 30px;
      
      h3 {
        margin: 0 0 10px 0;
        color: #303133;
        font-size: 18px;
      }
      
      p {
        margin: 0;
        color: #606266;
        font-size: 14px;
        line-height: 1.5;
      }
    }
    
    .auth-actions {
      display: flex;
      justify-content: center;
      gap: 12px;
      margin-top: 20px;
    }
  }
  
  .session-indicator {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 8px 12px;
    background: #f0f9ff;
    border: 1px solid #67c23a;
    border-radius: 6px;
    font-size: 12px;
    
    .el-tag {
      margin: 0;
    }
  }
}
</style>
